<template>
<div class="user-manage">
  <search-form-table :url="url" :isApiSearch="true" ref="searchtable" 
    :columns="columns" :form="form" :statusUrl="statusUrl" 
    statusIdKey="caseProductId" 
    statusTypeKey='caseProductType'
    :defaultParams="{
      caseProductType:0
    }" @search="handleSearch">
    <template slot="searchForm">
      <a-form layout="inline" :form="form">
        <a-form-item label="案例名称">
          <a-input
            v-decorator="[
              'caseProductName',
            ]"
            placeholder="请输入案例名称"
          >
          </a-input>
        </a-form-item>
        <a-form-item label="最后保存时间">
          <fast-range-picker style="width:240px"
            v-decorator="[
              'startTime-endTime'
            ]"
            >
          </fast-range-picker>
        </a-form-item>        
        <a-form-item label="图库所属">
          <a-select style="width: 180px" v-decorator="[
              'caseProductType',{
                initialValue:0
              }
            ]"  placeholder="请选择" :options="ownershipList" @change="handleProductTypeChange"></a-select>
        </a-form-item> 
      </a-form>
    </template>
    <template slot="oprationRow">
      <a-space>
        <permission authority="cases:productpublish:add" v-if="isShowPublishResult && shopType==1">
          <a-button type="primary" @click="publishStore($refs.searchtable.selectedRowKeys)">发布到门店</a-button>
        </permission>
        <permission authority="cases:product:add" v-if="isShowPublishResult">
          <a-button type="primary" icon="plus" @click="openNew()">新增案例</a-button>
        </permission>
        <permission authority="cases:product:delete">
          <a-button @click="deleteRows($refs.searchtable.selectedRowKeys)">删除</a-button>
        </permission>
      </a-space>
    </template>
    <template slot="tableOperation" slot-scope="{record}">
      <a-space>
        <!-- <permission>
          <span class="text-primary pointer" @click="publishStore(record)">发布到门店</span>
        </permission> -->
        <permission authority="cases:product:modify" v-if="isShowPublishResult">
          <span class="text-primary pointer" @click="openNew(record)">编辑</span>
        </permission>
        <permission authority="cases:product:delete">
          <span class="text-danger pointer" @click="deleteRows([record.id])">删除</span>
        </permission>
        <permission authority="cases:productpublish:add" v-if="isShowPublishResult && shopType==1">
          <span class="text-primary pointer" @click="publishStore([record.id])">发布到门店</span>
        </permission>
      </a-space>
    </template>
  </search-form-table>
  <new-products ref="newProduct" :record="currentRecord" @cancel="closeNewModal" :visible="newVisible"></new-products>
  <product-detail :record="currentRecord" @cancel="closeInfoModal" :visible="infoVisible"></product-detail>
  <ShopList ref="ShopListRef" :visible="publishVisible" :shopIds="shopIds" @cancel="publishVisible=false;" @submit="handleShopSubmit"></ShopList>
  <!-- <post-to-store  @cancel="closePublishModal" :visible="publishVisible"></post-to-store> -->

  <!-- <a-button @click="handleAddClassify">添加案例分类</a-button>
  <a-button @click="handleShowClassify">查询案例分类</a-button> -->
</div>
</template>
<script>
import NewProducts from './components/NewProducts'
import ProductDetail from './components/ProductDetail'
import { showPlatformList } from '@/utils/dictData'
import ShopList from '@/components/ShopList/ShopList';
import SearchFormTable from '@/components/ShopList/SearchFormTable';

export default {
  name: 'Role',
  data () {
    return {
      userIdTypeOptions: [{
        label: '店长',
        value: 1
      }, {
        label: '店员',
        value: 2
      }],
      url: '/cases/product/page',
      infoVisible: false,
      newVisible: false,
      currentRecord: {},
      form: this.$form.createForm(this, { name: 'table_search' }),
      columns: [
        {
          title: '产品图片',
          dataIndex: 'largeScreenPicture',
          key: 'largeScreenPicture',
          align: 'center',
          customRender: (text, row) => {
            console.log('text', text)
            return <table-img src={text}/>
          }
        },
        {
          title: '产品名称',
          dataIndex: 'caseProductName',
          key: 'caseProductName',
          customRender: (text, row) => {
            // console.log('row',row)
            return <a href='javascript:;' onClick={() => {
              this.currentRecord = row
              this.infoVisible = true
            }}>{text}</a>
          }
        },
        {
          title: '所属分类',
          dataIndex: 'casesClassificationName',
          key: 'casesClassificationName'
        },
        // {
        //   title:'所属店铺',
        //   dataIndex:'shopName',
        //   key:'shopName'
        // },
        {
          title: '排序',
          dataIndex: 'sort',
          key: 'sort'
        },
        {
          title: '展示平台',
          dataIndex: 'exhibitionPlatform',
          key: 'exhibitionPlatform',
          customRender: (text, row) => {
            let arr = text && text.split(',')
            let tmpData = []
            arr.forEach(val => {
              tmpData.push(this.getPlatformName(val))
            })
            return tmpData.join('/')
          }
        },
        {
          title: '上传员工',
          dataIndex: 'createByName', // 员工身份类型1店长2店员
          key: 'createByName'
        },
        {
          title:'是否展示',
          dataIndex:'enableShow',
          key:'enableShow',
          customRender: (text, record) => < a-switch checked={text == 1} onChange={() => this.onEnableShowChangeShow(record, text)} />
        },
        {
          title:'设为推荐',
          dataIndex:'enableRecommend',
          key:'enableRecommend',
          customRender: (text, record) => < a-switch checked={text == 1} onChange={() => this.onIsRecommendChangeShow(record, text)} />
        },
        {
          title: '最后保存时间',
          dataIndex: 'updateDate',
          key: 'updateDate'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      commodityIds:'',
      ownershipList:[
        {
          label:'本店案例',
          value:0,
        },{
          label:'其他案例',
          value:1,
        }
      ],
      statusUrl:'/cases/productpublish/update',
      publishVisible:false,
      shopIds:[],
      isShowPublish:true,
      isShowPublishResult:true,
    }
  },
  components: {
    NewProducts,
    ProductDetail,
    ShopList,
    SearchFormTable
  },
  computed:{
    userInfo(){
      return this.$store.getters.userInfo || {};
    },
    shopId(){
      return this.userInfo.shopId || '';
    },
    shopType(){
      let shopType=this.$route.query.shopType;
      if(shopType){
        return shopType;
      }
      if(this.userInfo.shopRoleCode=='role:store:main'){
        return 1;
      }
      else if(this.userInfo.shopRoleCode=='role:store:branch'){
        return 2;
      }
      else if(this.userInfo.shopRoleCode=='role:supplier'){
        return 3;
      }
    }//:1,//总店1；分店2；供应商3
  },
  mounted () {
  },
  methods: {
    // 测试数据
    // async handleAddClassify(){
    //   let res=await this.$post('/cases/classification/add',{
    //     parentId:'417489030494552065',
    //     caseName:'分类33333',
    //     pictureUrl:'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    //   })
    //   console.log(res)
    // },
    // async handleShowClassify(){
    //   let res=await this.$get('/cases/classification/list')
    //   console.log(res)
    // },
    handleProductTypeChange(e){
      console.log(e)
      this.isShowPublish=!e;
    },
    handleSearch(){
      this.isShowPublishResult=this.isShowPublish;
    },
    // 通过value展示名
    getPlatformName (value) {
      return showPlatformList.map(item => {
        if (item.value == value) {
          return item.label
        }
      }).filter(item => {
        return item
      })
    },
    publishStore (ids) {
      console.log(ids)
      if(ids.length==0){
        this.$message.error('请选择案例')
        return;
      }
      this.commodityIds=ids;
      this.publishVisible = true
    },
    closeNewModal (freshTable) {
      this.newVisible = false
      if (freshTable) {
        this.$refs.searchtable.refreshTable()
      }
    },
    // 设为推荐
    async onChangeShow(params) {
      let res = await this.$post(this.statusUrl, params);
      if (res && res.returnCode === 1000) {
        this.$message.success('操作成功!')
        this.$refs.searchtable.refreshTable()
      }
    },
    onEnableShowChangeShow(record, text) {
      this.onChangeShow({
        caseProductId: record.id,
        caseProductType: record.caseProductType,
        enableShow:  text == 1 ? 0 : 1,
      });
    },
    onIsRecommendChangeShow(record, text) {
      if(!record.enableShow){
        this.$message.error('请先打开展示状态!')
        return
      }
      this.onChangeShow({
        caseProductId: record.id,
        caseProductType: record.caseProductType,
        enableRecommend: text == 1 ? 0 : 1,
      });
    },
    openNew (record) {
      if (!record) {
        console.log('清空')
        this.$refs.newProduct.resetData()
      }
      this.currentRecord = record
      this.newVisible = true
    },
    closeInfoModal (freshTable) {
      this.infoVisible = false
      if (freshTable) {
        this.$refs.searchtable.refreshTable()
      }
    },
    openInfo (record) {
      this.currentRecord = record
      this.infoVisible = true
    },
    async handleShopSubmit(shopIds){
      let res=await this.$post('/cases/productpublish/add',{
        shopIds,
        productIds:this.commodityIds
      })
      if(res && res.returnCode=='1000'){
        this.$refs.ShopListRef.confirmLoading = false
        this.publishVisible=false;
        this.commodityIds=[];
        this.$message.success('发布成功！');
      } else {
        this.$refs.ShopListRef.confirmLoading = false
      }
    },
    deleteRows (ids) {
      // if (!ids || ids.length === 0) return this.$message.warn('请先选择一项后再进行操作')
      if (!ids || ids.length === 0) return this.$message.warn('请先选择一项后再进行操作')
      this.$confirm({
        title: '删除提示',
        content: '删除操作不可恢复，请确认是否删除？',
        okText: '确认删除',
        cancelText: '取消',
        onOk: () => {
          this.$post('/cases/product/delete', { ids,caseProductType:this.isShowPublishResult?0:1 }).then(res => {
            if (res && res.returnCode == 1000) {
              this.$message.success('删除成功')
              this.$refs.searchtable.refreshTable()
            }
          })
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>

</style>
